package pers.cz.codegen.dbtools;

import pers.cz.jefconfig.tools.StringUtils;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: LuoThinking-cloud
 * @description: 元数据信息操作
 * @author: Cheng Zhi
 * @create: 2022-08-08 11:16
 **/
public class MetaOperator extends DataBaseOperator {

    private String tableName;
    public MetaOperator() {
        super();
    }

    public MetaOperator(String tableName) {
        this.tableName = tableName;
    }

    /**
     * 获取所有表
     * @return
     * @throws SQLException
     */
    public List<TableInfo> getAllTables() throws SQLException {
        DatabaseMetaData metaData = connection.getMetaData();
        // 获取数据库名字
        String catalog = connection.getCatalog();
        // 获取schema
        String schema = connection.getSchema();
        // 从tableName中分离出scheme和table
        String[] split = StringUtils.split(tableName, "\\.");
        if (split.length == 2) {
            schema = split[0];
            tableName = split[1];
        }
        ResultSet tables = metaData.getTables(null, schema, tableName, new String[]{"TABLE"});

        List<TableInfo> tableInfos = new ArrayList<>();
        try {
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                String tableRemark = tables.getString("REMARKS");
                TableInfo tableInfo = new TableInfo();
                tableInfo.setCatalog(catalog);
                tableInfo.setSchema(schema);
                tableInfo.setTableName(tableName);
                tableInfo.setComment(tableRemark);

                setColumn(tableInfo, metaData);
                tableInfos.add(tableInfo);
            }
        } finally {
            tables.close();
        }

        return tableInfos;
    }


    private void setColumn(TableInfo tableInfo, DatabaseMetaData metaData) throws SQLException {

        List<ColumnInfo> columnInfos = new ArrayList<ColumnInfo>();
        String keyName = "";
        ResultSet columns = metaData.getColumns(tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getTableName(), null);
        // 将表名转化为首字母大写
        String capsTableName = StringUtils.getCamelCase(tableInfo.getTableName());
        // 获取主键
        ResultSet keySet = metaData.getPrimaryKeys(tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getTableName());
        while (keySet.next()) {
            keyName = keySet.getString(4);
        }

       try {
           while (columns.next()) {

               String coulumn = columns.getString("COLUMN_NAME");
               String columnType = JavaTypes.getType(columns.getInt("DATA_TYPE"));
               ColumnInfo columnInfo = new ColumnInfo();
               columnInfo.setCoulumnName(coulumn);
               columnInfo.setColumnType(columnType);
               columnInfo.setPrimary(false);
               Object comment = columns.getObject(12); // 获取列注释
               if (comment == null) {
                   columnInfo.setComment(null);
               } else {
                   columnInfo.setComment(comment.toString().isEmpty() ? coulumn : comment.toString());
               }

               if (coulumn.equals(keyName)) {
                   columnInfo.setPrimary(true);
               }
               columnInfos.add(columnInfo);
           }
       } finally {
           columns.close();
       }

        tableInfo.setColumnInfos(columnInfos);
    }

    @Override
    protected void finalize() throws Throwable {
        if (connection !=null) {
            connection.close();
        }

        if (statement != null) {
            statement.close();
        }
    }
}
